<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" prop="dateRange">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            @change="handleCommunityChange"
            style="width: 200px"
        >
          <el-option
              v-for="c in community"
              :key="c.communityId"
              :label="c.name"
              :value="c.communityId"
          ></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['charge:billa:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['charge:billa:remove']"
        >删除</el-button>
      </el-col>

      <!--支付和未支付状态的搜索按钮-->
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="List"
            @click="handleShowAll"
        >全部</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Check"
            @click="handlePaidFilter"
        >已支付</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Clock"
            @click="handleUnpaidFilter"
        >未支付</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['charge:billa:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="billaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账单编号" align="center" prop="billId" />
      <el-table-column label="社区名称" align="center" prop="communityName" />
      <el-table-column label="房屋号" align="center" prop="houseName" />
      <el-table-column label="收费项目" align="center" prop="chargeItemName" />
      <el-table-column label="账单日期" align="center" prop="billDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.billDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止日期" align="center" prop="dueDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="金额" align="center" prop="amount" />

      <el-table-column prop="gender" label="支付状态" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status===0" class="ml-2" type="success">已支付</el-tag>
          <el-tag v-else class="ml-2" type="warning">未支付</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['charge:billa:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['charge:billa:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改账单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <div style="color: red; font-size: 12px; margin-bottom: 10px;">
      </div>

      <el-form ref="billaRef" :model="form" :rules="rules" label-width="80px">
        <!-- 社区下拉框 -->
        <el-form-item label="社区">
          <el-select
              v-model="form.communityId"
              placeholder="请选择社区"
              clearable
              @change="gainCommunityId"
              style="width: 100%"
          >
            <el-option
                v-for="c in community"
                :key="c.communityId"
                :label="c.name"
                :value="c.communityId"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 楼宇下拉框 -->
        <el-form-item label="楼宇">
          <el-select
              v-model="form.buildingId"
              placeholder="请选择楼宇"
              clearable
              @change="gainBuildingId"
              style="width: 100%"
          >
            <el-option
                v-for="b in building"
                :key="b.buildingId"
                :label="b.name"
                :value="b.buildingId"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 房间号 -->
        <el-form-item label="房间号">
          <el-select
              v-model="form.houseId"
              placeholder="请选择房间号"
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="h in house"
                :key="h.houseId"
                :label="h.roomNo"
                :value="h.houseId"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 收费项目 -->
        <el-form-item label="收费项目">
          <el-select
              v-model="form.chargeItemId"
              placeholder="请选择收费项目"
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="i in chargeItem"
                :key="i.chargeItemId"
                :label="i.name"
                :value="i.chargeItemId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账单日期" prop="billDate">
          <el-date-picker clearable
                          v-model="form.billDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择账单日期"
                          style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>

        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker clearable
                          v-model="form.dueDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择截止日期"
                          style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Billa">
import { listBilla, getBilla, delBilla, addBilla, updateBilla } from "@/api/charge/billa"
import {parseTime} from "../../../utils/ruoyi.js";
import request from '@/utils/request'

const { proxy } = getCurrentInstance()

const billaList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 新增：时间段范围
const dateRange = ref([])

const data = reactive({
  form: {
    communityId: null,
    buildingId: null,
    houseId: null,
    chargeItemId: null,
    billDate: null,
    amount: null,
    dueDate: null,
    description: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    houseId: null,
    chargeItemId: null,
    billDate: null,
    amount: null,
    dueDate: null,
    status: null,
    paidAmount: null,
    paidTime: null,
    description: null,
    // 新增：时间段参数 - 使用 params 前缀
    params: {
      beginTime: null,
      endTime: null
    }
  },
  rules: {
    communityId: [
      { required: true, message: "社区不能为空", trigger: "change" }
    ],
    houseId: [
      { required: true, message: "房间号不能为空", trigger: "change" }
    ],
    chargeItemId: [
      { required: true, message: "收费项目不能为空", trigger: "change" }
    ],
    billDate: [
      { required: true, message: "账单日期不能为空", trigger: "change" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "blur" },
      { pattern: /^\d+(\.\d{1,2})?$/, message: "金额格式不正确", trigger: "blur" }
    ],
    dueDate: [
      { required: true, message: "截止日期不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 新增：处理时间段变化
function handleDateRangeChange(range) {
  console.log('时间段选择变化:', range)
  if (range && range.length === 2) {
    queryParams.value.params.beginTime = range[0]
    queryParams.value.params.endTime = range[1]
  } else {
    queryParams.value.params.beginTime = null
    queryParams.value.params.endTime = null
  }
  console.log('查询参数:', queryParams.value)
}

// 新增：处理查询条件中的社区变化
function handleCommunityChange(communityId) {
  queryParams.value.communityId = communityId
  console.log('选择社区:', communityId)

  // 如果选择了社区，显示社区名称
  if (communityId) {
    const selectedCommunity = community.value.find(c => c.communityId === communityId)
    console.log('选中的社区信息:', selectedCommunity)
  }
}

// 显示所有数据
function handleShowAll() {
  queryParams.value.status = null
  queryParams.value.communityId = null
  queryParams.value.pageNum = 1
  console.log('点击全部按钮，重置所有条件')
  getList()
}

// 搜索已支付账单
function handlePaidFilter() {
  queryParams.value.status = 0
  queryParams.value.pageNum = 1
  getList()
}

// 搜索未支付账单
function handleUnpaidFilter() {
  queryParams.value.status = 1
  queryParams.value.pageNum = 1
  getList()
}

// 社区下拉框绑定
const community = ref([]);
const building = ref([])
const house = ref([])
const chargeItem = ref([])

const initCommunity = () =>{
  request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data;
    console.log('加载社区数据:', community.value)
  }).catch(error => {
    console.error('加载社区数据失败:', error)
    proxy.$modal.msgError("加载社区数据失败")
  })
}

// 根据社区联动楼宇
const gainCommunityId = (cid) => {
  form.value.buildingId = null;
  form.value.houseId = null;
  building.value = [];
  house.value = [];

  if (cid){
    request({
      url: `/building/getBuildingVoNameAndId/${cid}`,
      method: 'get'
    }).then((response) => {
      building.value = response.data;
      console.log('加载楼宇数据:', building.value)
    }).catch(error => {
      console.error('加载楼宇数据失败:', error)
      proxy.$modal.msgError("加载楼宇数据失败")
    })
  }
}

// 根据楼宇再联动房屋
const gainBuildingId = (bid)=>{
  form.value.houseId = null;
  house.value = [];

  if (bid){
    request({
      url: `/houseVo/getHouseVoNameAndId/${bid}`,
      method: 'get'
    }).then((response) => {
      house.value = response.data.map(item => ({
        ...item,
        houseId: Number(item.houseId)
      }))
      console.log('加载房屋数据:', house.value)
    }).catch(error => {
      console.error('加载房屋数据失败:', error)
      proxy.$modal.msgError("加载房屋数据失败")
    })
  }
}

// 绑定收费项目的下拉框
const initChargeItem = () =>{
  request({
    url: `/charge/itema/getChargeItem?t=${new Date().getTime()}`,
    method: 'get'
  }).then((response) => {
    chargeItem.value = response.data;
    console.log('加载收费项目数据:', chargeItem.value)
  }).catch(error => {
    console.error('加载收费项目数据失败:', error)
    proxy.$modal.msgError("加载收费项目数据失败")
  })
}

/** 查询账单管理列表 */
function getList() {
  loading.value = true
  console.log('发送查询参数:', queryParams.value)

  listBilla(queryParams.value).then(response => {
    billaList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log('返回的数据条数:', response.rows.length)
  }).catch((error) => {
    console.error('查询失败:', error)
    loading.value = false
    proxy.$modal.msgError("查询失败")
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    billId: null,
    communityId: null,
    buildingId: null,
    houseId: null,
    chargeItemId: null,
    billDate: null,
    amount: null,
    dueDate: null,
    description: null
  }
  building.value = []
  house.value = []
  proxy.resetForm("billaRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  console.log('搜索按钮点击，查询参数:', queryParams.value)
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  // 清空时间段选择器
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.status = null
  queryParams.value.communityId = null
  queryParams.value.params.beginTime = null
  queryParams.value.params.endTime = null
  console.log('重置后查询参数:', queryParams.value)
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.billId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  initChargeItem();
  open.value = true
  title.value = "添加账单管理"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  initChargeItem();
  const _billId = row.billId || ids.value

  try {
    const response = await getBilla(_billId)
    form.value = response.data

    // 关键修复：统一数据类型
    if (form.value.houseId) {
      form.value.houseId = Number(form.value.houseId)
    }

    // 步骤1：加载社区的所有楼宇
    if (form.value.communityId) {
      const buildingResponse = await request({
        url: `/building/getBuildingVoNameAndId/${form.value.communityId}`,
        method: 'get'
      })
      building.value = buildingResponse.data
    }

    // 步骤2：查找正确的楼宇ID
    if (!form.value.buildingId && form.value.houseId && building.value.length > 0) {
      for (const b of building.value) {
        try {
          const houseResponse = await request({
            url: `/houseVo/getHouseVoNameAndId/${b.buildingId}`,
            method: 'get'
          })

          const foundHouse = houseResponse.data.find(h => Number(h.houseId) === form.value.houseId)
          if (foundHouse) {
            form.value.buildingId = b.buildingId

            // 关键修复：转换房屋数据的类型
            house.value = houseResponse.data.map(item => ({
              ...item,
              houseId: Number(item.houseId)
            }))
            break
          }
        } catch (error) {
          console.error('获取楼宇房屋数据失败:', error)
        }
      }
    }

    // 步骤3：如果还是没找到，设置一个默认楼宇ID
    if (!form.value.buildingId && building.value.length > 0) {
      form.value.buildingId = building.value[0].buildingId

      // 加载该楼宇的房屋
      const houseResponse = await request({
        url: `/houseVo/getHouseVoNameAndId/${form.value.buildingId}`,
        method: 'get'
      })

      // 关键修复：转换房屋数据的类型
      house.value = houseResponse.data.map(item => ({
        ...item,
        houseId: Number(item.houseId)
      }))
    }

    open.value = true
    title.value = "修改账单管理"

  } catch (error) {
    console.error('获取账单数据失败:', error)
    proxy.$modal.msgError("获取账单数据失败")
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["billaRef"].validate(valid => {
    if (valid) {
      if (form.value.billId != null) {
        updateBilla(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(() => {})
      } else {
        addBilla(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(() => {})
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _billIds = row.billId || ids.value
  proxy.$modal.confirm('是否确认删除账单管理编号为"' + _billIds + '"的数据项？').then(function() {
    return delBilla(_billIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('charge/billa/export', {
    ...queryParams.value
  }, `billa_${new Date().getTime()}.xlsx`)
}

// 初始化
getList()
initCommunity()
initChargeItem()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}

/* 确保下拉框有足够的宽度 */
.el-select {
  width: 100%;
}

/* 查询表单中的下拉框样式 */
.el-form-item .el-select {
  min-width: 200px;
}
</style>